package com.xxkj.orcfx.service;

import com.xxkj.orcfx.UserSettings;
import com.xxkj.orcfx.utils.CommonUtils;
import com.xxkj.orcfx.web.Resp;
import com.xxkj.orcfx.web.UserQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


public class OcrService  {
    private Logger log = LoggerFactory.getLogger(OcrService.class);

    public boolean checkLogin() {
        boolean isLogin = false;
        try {
            Thread.sleep(500L);
            UserSettings userSettings = new UserSettings();
            if (StringUtils.isBlank(userSettings.getCookieCid()) || StringUtils.isBlank(userSettings.getCookieSessionId())) {
                return isLogin;
            }
            String url = "http://zxgk.court.gov.cn/zhzxgk/";
            String cookieStr = "wzws_sessionid=" + userSettings.getCookieSessionId() + "; wzws_cid=" + userSettings.getCookieCid();
            log.info("登录验证 cookie:{}", cookieStr);
            BasicCookieStore cookieStore = new BasicCookieStore();
            HttpClient httpClient = HttpClients.custom()
                    .setDefaultRequestConfig(RequestConfig.custom()
                            .setConnectTimeout(50000) // 设置连接超时时间
                            .setSocketTimeout(50000) // 设置读取超时时间
                            .build())
                    .setDefaultCookieStore(cookieStore)
                    .build();

            // 创建HttpGet请求
            HttpGet httpGet = new HttpGet(url);

            // 设置请求头
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
            httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
            httpGet.setHeader("Host", "zxgk.court.gov.cn");
            httpGet.setHeader("Connection", "keep-alive");
            httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpGet.setHeader("Cookie", cookieStr);// 设置Cookie
            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpGet);

            for (Cookie cookie : cookieStore.getCookies()) {
                if (StringUtils.equals(cookie.getName(), "JSESSIONID")) {
                    userSettings.saveCookieProperties("", "", cookie.getValue());
                }
            }

            // 打印响应内容
            String responseBody = EntityUtils.toString(response.getEntity(), "utf-8");
            String title = CommonUtils.extractTitle(responseBody);
            if (StringUtils.contains(title, "全国法院信息")) {
                isLogin = true;
                log.info("登录验证成功,title:{}", title);
            } else {
                log.info("登录验证失败,title:{}", title);
            }
            // 释放资源
            EntityUtils.consume(response.getEntity());

        } catch (Exception ex) {
            log.error("检查登录异常", ex);
            //ex.printStackTrace();
        }

        return isLogin;
    }

    public void doLogin() {
        try {
            Thread.sleep(600L);
            UserSettings userSettings = new UserSettings();
            BasicCookieStore cookieStore = new BasicCookieStore();
            // 创建HttpClient，并设置cookie store
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            // 第二步：请求验证码并且识别
            String step1Url = "http://zxgk.court.gov.cn/waf_text_captcha";
            log.info("第一步-获取验证码地址:{}", step1Url);
            HttpGet getRequest2 = new HttpGet(step1Url); // 第一步验证码页面
            getRequest2.setHeader(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"));
            getRequest2.setHeader(new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"));
            getRequest2.setHeader(new BasicHeader("Accept-Language", "zh-CN,zh;q=0.9"));
            getRequest2.setHeader(new BasicHeader("Host", "zxgk.court.gov.cn"));
            getRequest2.setHeader(new BasicHeader("Connection", "keep-alive"));
            // 执行GET请求
            HttpResponse response = httpClient.execute(getRequest2);
            String captchaFileName = "";
            // 检查响应状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream inputStream = response.getEntity().getContent();
                //保存图片到本地，生成日期格式的文件名
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                captchaFileName = "image_" + timeStamp + ".jpg"; // 修改文件扩展名为实际文件类型
                File file = new File(captchaFileName);
                // 将输入流中的数据写入到本地文件
                FileOutputStream outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                // 关闭输出流
                outputStream.close();
            } else {
                throw new RuntimeException("第一步访问验证,获取状态码失败. HTTP Error Code:" + response.getStatusLine().getStatusCode());
            }
            String sessionId = "";
            String cid = "";
            for (Cookie cookie : cookieStore.getCookies()) {
                if (StringUtils.equals(cookie.getName(), "wzws_sessionid")) {
                    sessionId = cookie.getValue();
                } else if (StringUtils.equals(cookie.getName(), "wzws_cid")) {
                    cid = cookie.getValue();
                }
            }
            userSettings.saveCookieProperties(cid, sessionId, "");

            EntityUtils.consume(response.getEntity());

            log.info("第一步,cid:{},sessionId:{}", cid, sessionId);
            File captchaFile = new File(captchaFileName);
            String stepOneCaptchaCode = CommonUtils.getCaptchaCode(captchaFile);//第一步验证码
            log.info("第一步,识别验证码结果:{}", stepOneCaptchaCode);
            captchaFile.deleteOnExit();
            String text_verify_url = "http://zxgk.court.gov.cn/waf_text_verify.html?captcha=" + stepOneCaptchaCode;
            log.info("第二步,验证码输入,地址:{}", text_verify_url);
            String cookieStr = "wzws_sessionid=" + userSettings.getCookieSessionId() + "; wzws_cid=" + userSettings.getCookieCid();

            BasicCookieStore cookieStore2 = new BasicCookieStore();
            HttpClient httpClient2 = HttpClients.custom()
                    .setRedirectStrategy(new DefaultRedirectStrategy() {
                        @Override
                        protected boolean isRedirectable(String method) {
                            return false; // 禁用自动重定向
                        }
                    })// 使用 LaxRedirectStrategy 处理重定向
                    .setDefaultRequestConfig(RequestConfig.custom()
                            .setConnectTimeout(50000) // 设置连接超时时间
                            .setSocketTimeout(50000) // 设置读取超时时间
                            .build())
                    .setDefaultCookieStore(cookieStore2)
                    .build();

            // 创建HttpGet请求
            HttpGet httpGet = new HttpGet(text_verify_url);
            // 设置请求头
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
            httpGet.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
            httpGet.setHeader("Host", "zxgk.court.gov.cn");
            httpGet.setHeader("Connection", "keep-alive");
            httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpGet.setHeader("Cookie", cookieStr);// 设置Cookie
            // 发送请求并获取响应
            HttpResponse response2 = httpClient2.execute(httpGet);
            // 打印响应状态码
            System.out.println("Response Code : " + response2.getStatusLine().getStatusCode());
            for (Cookie cookie : cookieStore2.getCookies()) {
                System.out.println("Response Cookie: " + cookie.getName() + " = " + cookie.getValue());
                if (StringUtils.equals("wzws_cid", cookie.getName())) {
                    userSettings.saveCookieProperties(cookie.getValue(),"","");
                }
            }
            // 打印响应内容
            String responseBody = EntityUtils.toString(response2.getEntity(), "utf-8");
            String title2 = CommonUtils.extractTitle(responseBody);
            // 释放资源
            log.info("第二步,验证码输入结果,状态码:{},标题:{}", response2.getStatusLine().getStatusCode(), title2);
            EntityUtils.consume(response2.getEntity());
            // log.info("第二步,cookieVar:{}", JSONObject.toJSONString(cookieVar));
        } catch (Exception ex) {
            log.error("第一步登录异常", ex);
        }
    }

    public Resp<String> doSubmit(UserQuery userQuery) {
        try {
            Thread.sleep(600L);
            UserSettings userSettings = new UserSettings();

            HttpClient httpClient = HttpClients.custom()
                    .setDefaultRequestConfig(RequestConfig.custom()
                            .setConnectTimeout(50000) // 设置连接超时时间
                            .setSocketTimeout(50000) // 设置读取超时时间
                            .build())
                    //.setDefaultCookieStore(cookieStore)
                    .build();
            String captchaId = CommonUtils.getNum().replaceAll("-", "");
            String cookieStr = "JSESSIONID=" + userSettings.getJSessionId() + ";wzws_sessionid=" + userSettings.getCookieSessionId() + "; wzws_cid=" + userSettings.getCookieCid();
            log.info("第三步,请求cookie:{}", cookieStr);
            Random random = new Random();
            double randomNumber = random.nextDouble();
            String randomNumberStr = String.valueOf(randomNumber);
            String queryURL = "http://zxgk.court.gov.cn/zhzxgk/captcha.do?captchaId=" + captchaId + "&random=" + randomNumberStr;
            System.out.println("查询页面的验证码地址: " + queryURL);
            log.info("第三步,查询页面的验证码地址:{}", queryURL);
            HttpGet httpGet = new HttpGet(queryURL); // 替换为需要使用cookie的URL
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
            httpGet.setHeader("Accept", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8");
            httpGet.setHeader("Host", "zxgk.court.gov.cn");
            httpGet.setHeader("Connection", "keep-alive");
            httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpGet.setHeader("Cookie", cookieStr);// 设置Cookie
            HttpResponse response = httpClient.execute(httpGet);
            String captchaQueryName = "";
            // 检查响应状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream inputStream = response.getEntity().getContent();
                // 定义本地文件路径
                // 生成日期格式的文件名
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                captchaQueryName = "image_query_" + timeStamp + ".jpg"; // 修改文件扩展名为实际文件类型
                File file = new File(captchaQueryName);
                // 将输入流中的数据写入到本地文件
                FileOutputStream outputStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                // 关闭输出流
                outputStream.close();
            }

            EntityUtils.consume(response.getEntity());
            File captchaQueryFile = new File(captchaQueryName);
            String queryCaptchaCode = CommonUtils.getCaptchaCode(captchaQueryFile);
            if (StringUtils.isBlank(queryCaptchaCode)) {
                return Resp.fail("第三步,查询结果页面的验证码异常，请联系管理员");
            }
            captchaQueryFile.deleteOnExit();//删除文件

            log.info("第三步,查询结果页面的验证码结果:{}", queryCaptchaCode);

            HttpPost httpPost5 = new HttpPost("http://zxgk.court.gov.cn/zhzxgk/searchZhcx.do"); // 替换为需要使用cookie的URL
            // 设置请求头
            httpPost5.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpPost5.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            httpPost5.setHeader("Cookie", cookieStr);// 设置Cookie
            httpPost5.setHeader("Referer", "http://zxgk.court.gov.cn/zhzxgk/");
            httpPost5.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
            httpPost5.setHeader("Host", "zxgk.court.gov.cn");
            httpPost5.setHeader("Connection", "keep-alive");
            httpPost5.setHeader("Accept-Language", "zh-CN,zh;q=0.9");

            List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("pName", userQuery.getName()));
            nvps.add(new BasicNameValuePair("pCardNum", userQuery.getIdCardNo()));
            nvps.add(new BasicNameValuePair("selectCourtId", "0"));
            nvps.add(new BasicNameValuePair("pCode", queryCaptchaCode));
            nvps.add(new BasicNameValuePair("captchaId", captchaId));
            nvps.add(new BasicNameValuePair("searchCourtName", "全国法院（包含地方各级法院）"));
            nvps.add(new BasicNameValuePair("selectCourtArrange", "1"));
            nvps.add(new BasicNameValuePair("currentPage", "1"));
            httpPost5.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            HttpResponse response5 = httpClient.execute(httpPost5);
            // 读取响应内容
            String responseBody = EntityUtils.toString(response5.getEntity(), "utf-8");
            String caseCodeTxt = CommonUtils.getRspResult(responseBody);
            log.info("第三步，查询返回结果：{}", responseBody);
            log.info("第三步，解析查询结果：{}", caseCodeTxt);
            // 释放资源
            EntityUtils.consume(response5.getEntity());
            return Resp.success(caseCodeTxt);
        } catch (Exception ex) {
            log.error("第三步查异常", ex);
            return Resp.fail("系统异常");
        }

    }


    public Resp<String> doQuery(UserQuery userQuery) {
        if (!this.checkLogin()) {
            this.doLogin();
            boolean isLogin = this.checkLogin();
            if (isLogin) {
                return doSubmit(userQuery);
            } else {
                return Resp.fail("登录异常，请联系管理员");
            }
        } else {
            return doSubmit(userQuery);
        }
    }

}
